/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦]
 * 
 * https://zhiqim.org/project/zhiqim_framework/zhiqim_kernel.htm
 *
 * Zhiqim Kernel is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.kernel.xml.parser;

import org.w3c.dom.Node;
import org.zhiqim.kernel.constants.XmlConstants;
import org.zhiqim.kernel.util.Ints;
import org.zhiqim.kernel.util.Longs;
import org.zhiqim.kernel.util.Strings;
import org.zhiqim.kernel.xml.Xml;
import org.zhiqim.kernel.xml.XmlParser;
import org.zhiqim.kernel.xml.Xmls;

/**
 * 基本类型适配器，格式如下：
 * <ID>19202129384</ID>
 *
 * @version v1.1.2 @author zouzhigang 2015-8-21 新建与整理
 */
public class BaseParser implements XmlParser, XmlConstants
{
    @Override
    public XmlParser set(Xml xmlMain)
    {
        return this;
    }
    
    @Override
    public String toStringInner(Object obj, String tagName, int tagLevel)
    {
        StringBuilder strb = new StringBuilder();
        Strings.addNewLine(strb);
        Strings.addTwoSpace(strb, tagLevel);
        
        Xmls.addTagBegin(strb, tagName);
        if (obj instanceof String && ((String)obj).contains("<"))
            strb.append(_CDATA).append(obj).append(CDATA_);
        else
            strb.append(obj);
        Xmls.addTagEnd(strb, tagName);
        return strb.toString();
    }
    
    @Override
    public Object toObjectInner(Node node, Class<?> clazz, Class<?> generics)
    {
        if (node == null)
        {//没有节点返回null
            return null;
        }
        
        String xml = node.getTextContent();
        if (clazz == boolean.class || clazz == Boolean.class)
            return Boolean.parseBoolean(xml);
        else if (clazz == byte.class || clazz == Byte.class)
            return Byte.parseByte(xml);
        else if (clazz == char.class || clazz == Character.class)
            return xml.charAt(0);
        else if (clazz == short.class || clazz == Short.class)
            return Short.parseShort(xml);
        else if (clazz == int.class || clazz == Integer.class)
            return Ints.toInt(xml);
        else if (clazz == long.class || clazz == Long.class)
            return Longs.toLong(xml);
        else if (clazz == float.class|| clazz == Float.class)
            return Float.parseFloat(xml);
        else if (clazz == double.class || clazz == Double.class)
            return Double.parseDouble(xml);
        else if (clazz == String.class)
            return xml;
        else
            return null;
    }
}
